﻿using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraReports.UI;
using Luna小店.DTO;
using Luna小店.report;
using Luna小店.service;
using Luna小店.service.redis_service;
using Luna小店.UC.任务;
using Luna小店.UC.款式异常;
using Luna小店.Utils;
using Luna小店.原型;
using mendian;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using static Luna小店.service.TaskService;
using static Luna小店.原型.TaskDTOS;

namespace Luna小店.UC.门店下单.form.样品
{
    public partial class Frm样衣订单预览 : DevExpress.XtraEditors.XtraForm
    {
        private Enum任务类别 enum任务类别 = Enum任务类别.销售任务;
        public UC销售备注模板 uc销售备注模板 = new UC销售备注模板();
        public TaskDTOS TaskDTOS = new TaskDTOS();
        public TaskDTO TaskDTO = new TaskDTO();
        private 门店下单选款式Model model;
        private String Style_Id;
        private String ORDER_ID;
        private String REMARKS;
        public DTO样衣下单任务 dto样衣下单任务;
        private String remark_id;
        public ImageUtil imageUtil { get; set; }
        public 面料样品DTO dto面料样品 { get; set; } = new 面料样品DTO();
        //private List<尺寸呈现dto> 尺寸呈现 = new List<尺寸呈现dto>();
        private Dictionary<String, String> template_choose = new Dictionary<string, string>();//模板名称和id
        public Frm样衣订单预览(String Style_Id, List<尺寸呈现dto> lst, String ORDER_ID, String REMARKS)
        {
            InitializeComponent();
            this.xtraTabPager任务预览.PageVisible = false;
            this.Style_Id = Style_Id;
            this.ORDER_ID = ORDER_ID;
            this.REMARKS = REMARKS;

            //  订单相关信息
            this.model = new 门店下单选款式Model(ORDER_ID)
                .build尺寸呈现(lst)
                .build款式全尺寸(Style_Id)
                .build设计点(Style_Id)
                .build款式图片();
            //  this.model.build订单Model()
            //  控件行为
            //try
            //{
            //    this.dto面料样品 = new 面料样品DTO(FabricService.GetDRFromt_sample_material(this.ORDER_ID));
            //}
            //catch
            //{
            //}
            //this.model.面料信息 = FabricService.Add样衣物料信息(this.model.面料信息, this.dto面料样品);
            this.gridControl款式.DataSource = this.model.款式图片一览;
            this.gridControl面料.DataSource = this.model.面料信息;
            this.gridControlSize.DataSource = this.model.尺寸呈现;
            //this.gridControl设计点.DataSource = this.model.Dto定制下单.Dto设计点s;
            //  模板  TODO
            //((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items.Add("样品下单");
            //((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items.Add("定制下单");
            //this.barEditItemTemplate.EditValue = ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items[0];
        }
        public Frm样衣订单预览(String Styleid,String data,String remark_id)
        {
            InitializeComponent();
            this.xtraTabPager任务预览.PageVisible = false;
            this.Style_Id = Styleid;
            this.dto样衣下单任务 = FunctionHelper.JsonDeserialization<DTO样衣下单任务>(data);
            this.remark_id = remark_id;
            this.model = new 门店下单选款式Model()
                .build款式全尺寸(Style_Id)
                .build设计点(Style_Id);
            this.gridControl款式.DataSource = this.model.款式图片一览;
            this.gridControl面料.DataSource = this.model.面料信息;
            this.gridControlSize.DataSource = this.model.尺寸呈现;
        }
        private void gridViewSize_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            this.model.尺寸呈现[e.RowHandle]  //  DTO
                .SizeConflict() //  尺寸冲突
                .build尺寸增减值(e.Column.FieldName, e.Value.ToString());   //  根据修改列修改尺寸值

            //  尺寸计算
            foreach (尺寸呈现dto dto in this.model.尺寸呈现)
            {
                dto.CountSize();
            }

            //  保存入数据库
            this.model.build尺寸保存();
            SizeService.save设计点(this.Style_Id, this.model.Dto定制下单.Dto尺寸);

            //  刷新
            this.gridControlSize.DataSource = this.model.尺寸呈现;
            this.gridControlSize.Refresh();
        }

        private void gridViewSize_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            //e.Appearance.BackColor = Color.NavajoWhite;
            if (e.Column.Name == "colGarment")
            {
                if (this.model.尺寸呈现[e.RowHandle].OUT_VALUE > this.model.尺寸呈现[e.RowHandle].leastReasonable)
                {
                    //该行数据的该列的值不为空时时,其背景色为Red
                    e.Appearance.BackColor = Color.Red;//设置单元格变色
                                                       //e.Column.AppearanceCell.BackColor = Color.Red;//设置数据列变色
                }
                else if (this.model.尺寸呈现[e.RowHandle].IN_VALUE > this.model.尺寸呈现[e.RowHandle].maxReasonable)
                {
                    //该行数据的该列的值不为空时时,其背景色为Red
                    e.Appearance.BackColor = Color.Green;//设置单元格变色
                                                         //e.Column.AppearanceCell.BackColor = Color.Red;//设置数据列变色
                }
                else
                {
                    e.Appearance.BackColor = Color.CornflowerBlue;
                }
            }
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            new Frm面料选择(this.model.Dto定制下单.Style_Id, Frm面料选择.Enum选择面料类型.全部, this.model, this.Style_Id).ShowDialog();
        }

        private void Frm尺寸修改子页_Activated(object sender, EventArgs e)
        {
            //this.mianliaoname.Text = this.model.面料信息[0].name;
            //this.gridControl面料.DataSource = this.model.面料信息;
            this.tileView2.RefreshData();
            this.gridView1.RefreshData();
            //this.TaskDTOS.buildTaskDTOs(this.ORDER_ID);
            this.TaskDTOS.buildTaskDTOs(this.remark_id, this.Style_Id);
            this.treeList任务流程.DataSource = this.TaskDTOS.taskDTOs;
            this.gridControl导航.DataSource = this.TaskDTOS.taskDTOs;
            this.gridControl导航.Refresh();
            try
            {
                foreach (TaskDTO taskDTO in this.TaskDTOS.taskDTOs)
                {
                    if (taskDTO.template_id == ((int)Enum样衣子任务.面料任务).ToString())
                    {
                        this.richEditControl辅配料.ReadOnly = true;
                        this.richEditControl辅配料.Refresh();
                        byte[] decBytes = Convert.FromBase64String(taskDTO.remark);
                        FileBinaryConvertHelper.Bytes2File(decBytes, @"" + taskDTO.file_name + ".doc");
                        this.richEditControl辅配料.LoadDocument(@"" + taskDTO.file_name + ".doc");
                        File.Delete(@"" + this.TaskDTO.file_name + ".doc");
                    }
                    if (taskDTO.template_id == ((int)Enum样衣子任务.设计点任务).ToString())
                    {
                        this.richEditControl设计点描述.ReadOnly = true;
                        this.richEditControl设计点描述.Refresh();
                        byte[] decBytes = Convert.FromBase64String(taskDTO.remark);
                        FileBinaryConvertHelper.Bytes2File(decBytes, @"" + taskDTO.file_name + ".doc");
                        this.richEditControl设计点描述.LoadDocument(@"" + taskDTO.file_name + ".doc");
                        File.Delete(@"" + this.TaskDTO.file_name + ".doc");
                    }
                }
            }
            catch (Exception ex)
            {
//                MessageBox.Show("当前时间：" + DateTime.Now.ToString() + "\n" +
//"异常信息：" + ex.Message + "\n" +
//"异常对象：" + ex.Source + "\n" +
//"调用堆栈：\n" + ex.StackTrace.Trim() + "\n" +
//"触发方法：" + ex.TargetSite + "\n");
            }
            try
            {
                this.dto面料样品 = new 面料样品DTO(FabricService.GetDRFromt_sample_material(this.ORDER_ID));
            }
            catch
            {
            }
            this.model.面料信息 = FabricService.Add样衣物料信息(this.model.面料信息, this.dto面料样品);
            this.gridControl面料.DataSource = this.model.面料信息;
            try
            {
                this.pictureBox面料小样.Image = this.dto面料样品.SAMPLE_PIC;
            }
            catch
            {
            }
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //this.layoutControl1.SaveLayoutToXml(this.barEditItemTemplate.EditValue+".xml");
        }

        private void repositoryItemComboBox1_EditValueChanged(object sender, EventArgs e)
        {
            //this.layoutControl1.RestoreLayoutFromXml("layout_xml\\" + this.barEditItemTemplate.EditValue + ".xml");
            //this.richEditControl备注.LoadDocument("文档模板\\" + this.barEditItemTemplate.EditValue + ".docx");
        }

        private void tileView1_ItemDoubleClick(object sender, DevExpress.XtraGrid.Views.Tile.TileViewItemClickEventArgs e)
        {
            //new Frm设计点(this.model.Dto定制下单.Dto设计点s[this.tileView1.FocusedRowHandle], Enum选择设计点类型.全部, this.Style_Id).ShowDialog();
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("是否保存",
        "Saving a document", MessageBoxButtons.YesNo) == DialogResult.Yes)
                try
                {
                    //richEditControl备注.SaveDocument(@"" + this.ORDER_ID + ".doc", DevExpress.XtraRichEdit.DocumentFormat.Doc);
                    //Byte[] byteArray = FileBinaryConvertHelper.File2Bytes(@"" + this.ORDER_ID + ".doc");
                    //String str = Convert.ToBase64String(byteArray);
                    //FileService.SaveRemarkFile(str, this.ORDER_ID + ".doc", this.ORDER_ID);
                    //File.Delete(this.ORDER_ID + ".doc");
                    //switch (this.template_choose[this.barEditItem模板.EditValue.ToString()])
                    switch (this.TaskDTO.template_id)
                    {
                        case "1":
                            this.uc销售备注模板.SaveToDTO();
                            break;
                    }
                    this.TaskDTO.buildserial_number().buildStatus(1).SaveInMTM();
                    MessageBox.Show("保存成功");
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败" + ex.Message);
                }

        }

        private void Frm尺寸修改子页_Load(object sender, EventArgs e)
        {
            //this.xtraTabControl1.SelectedTabPage = this.xtraTabPager任务预览;
            //DataTable dt = TaskQueryFacadeService.GetTemplate();
            //foreach (DataRow dr in dt.Rows)
            //{
            //    this.template_choose.Add(dr["template_name"].ToString(), dr["template_id"].ToString());
            //    ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)barEditItem模板.Edit).Items.Add(dr["template_name"].ToString());
            //}
        }

        //private void barButtonItem新增模板_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    if (this.barEditItem模板.EditValue == null)
        //    {
        //        return;
        //    }
        //    this.TaskDTO = new TaskDTO().buildNewDTO(this.template_choose[this.barEditItem模板.EditValue.ToString()], this.ORDER_ID, this.Style_Id, "1");
        //    try
        //    {
        //        //switch (this.template_choose[this.barEditItem模板.EditValue.ToString()])
        //        //{
        //        //    case "1":
        //        //        this.uc销售备注模板 = new UC销售备注模板(this.任务DTO, true);
        //        //        uc销售备注模板.Dock = DockStyle.Fill;
        //        //        this.panel1.Controls.Add(uc销售备注模板);
        //        //        this.panel1.Refresh();


        //        //        break;
        //        //}
        //        new Frm任务(this.TaskDTO, true).ShowDialog();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("当前时间：" + DateTime.Now.ToString() + "\n" +
        //        "异常信息：" + ex.Message + "\n" +
        //        "异常对象：" + ex.Source + "\n" +
        //        "调用堆栈：\n" + ex.StackTrace.Trim() + "\n" +
        //        "触发方法：" + ex.TargetSite + "\n");
        //    }
        //}

        private void gridView一览_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            this.TaskDTO = new TaskDTO().buildRead(this.gridView一览.GetRowCellValue(e.RowHandle, "remark_id").ToString());
            //switch (this.gridView一览.GetRowCellValue(e.RowHandle, "template_id").ToString())
            //{
            //    case "1":
            //        this.uc销售备注模板 = new UC销售备注模板(this.任务DTO, false); uc销售备注模板.Dock = DockStyle.Fill;
            //        this.panel1.Controls.Clear();
            //        this.panel1.Controls.Add(uc销售备注模板);
            //        this.panel1.Refresh();
            //        break;
            //}
            new Frm任务(this.TaskDTO, false).ShowDialog();
        }
        /// <summary>
        /// 任务预览
        /// </summary>
        /// <param name="Style_Id"></param>
        /// <param name="lst"></param>
        /// <param name="ORDER_ID"></param>
        /// <param name="REMARKS"></param>
        /// <param name="tab"></param>
        public Frm样衣订单预览(String Style_Id, List<尺寸呈现dto> lst, String ORDER_ID, String REMARKS, String remark_id, Enum任务类别 @enum)
        {
            InitializeComponent();
            this.enum任务类别 = @enum;
            this.Style_Id = Style_Id;
            this.ORDER_ID = ORDER_ID;
            this.model = new 门店下单选款式Model(ORDER_ID);    //  传入ORDER_ID，取得STYLE_ID
            this.model.尺寸呈现 = lst;
            this.REMARKS = REMARKS;            

            //  订单相关信息
            this.model
                .build款式全尺寸()   //  取得尺寸和面料
                //.build设计点(Style_Id) //  根据styleid取得设计点
                .build款式图片();   //  根据ORDER_ID取得款式图

            //  控件行为
            this.gridControl款式.DataSource = this.model.款式图片一览;
            this.gridControl面料.DataSource = this.model.面料信息;
            this.gridControlSize.DataSource = this.model.尺寸呈现;
            //this.gridControl设计点.DataSource = this.model.Dto定制下单.Dto设计点s;
            //  模板  TODO
            //((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items.Add("样品下单");
            //((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items.Add("定制下单");
            //this.barEditItemTemplate.EditValue = ((DevExpress.XtraEditors.Repository.RepositoryItemComboBox)this.barEditItemTemplate.Edit).Items[0];
            if (enum任务类别 == Enum任务类别.生产任务)
            {
                this.TaskDTO = new TaskDTO().buildFromErp(remark_id);
            }
            if (enum任务类别 == Enum任务类别.销售任务)
            {
                this.TaskDTO = new TaskDTO().buildRead(remark_id);
            }
            switch (this.TaskDTO.template_id)
            {
                case "1":
                    this.uc销售备注模板 = new UC销售备注模板(this.TaskDTO, false); uc销售备注模板.Dock = DockStyle.Fill;
                    this.panel任务预览.Controls.Clear();
                    this.panel任务预览.Controls.Add(uc销售备注模板);
                    this.panel任务预览.Refresh();
                    break;
            }
            TaskService.UpdataStatus(remark_id, "MS_02");//更新任务状态
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            订单Model 订单Model = this.model.build订单Model();
            new OrderRedisService().saveOrder(
                订单Model
                , TaskQueryFacadeService.getUserTasksByOrderId(订单Model.ORDER_ID)
                );
            print条码();
            //TaskService.SaveFileToErp(this.TaskDTOS);
            OrderService.UpdataOrderPrintFlag(this.ORDER_ID, true);//更改订单打印状态
        }
        /// <summary>
        /// 打印订单条码
        /// </summary>
        public void print条码()
        {
            Engine btEngine = new Engine();
            btEngine.Start();
            //string lj = AppDomain.CurrentDomain.BaseDirectory + "顺丰订单模板.btw";  //test.btw是BT的模板
            //string lj = AppDomain.CurrentDomain.BaseDirectory + "001.btw";  //test.btw是BT的模板
            String lj2 = "C:\\002.btw";
            LabelFormatDocument btFormat = btEngine.Documents.Open(lj2);
            //指定打印机名 
            //btFormat.PrintSetup.PrinterName = "HPRT HLP106S-UE";
            //btFormat.PrintSetup.PrinterName = "TEC";
            btFormat.PrintSetup.PrinterName = "POSTEK G-3106";
            //打印份数                   
            btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
            //改变标签打印数份连载 
            btFormat.PrintSetup.NumberOfSerializedLabels = 2;
            //对BTW模版相应字段进行赋值 

            btFormat.SubStrings["styleid"].Value = this.ORDER_ID;
            Messages messages1;
            int waitout1 = 10000; // 10秒 超时 
            Result nResult2 = btFormat.Print("订单条码" + this.ORDER_ID, waitout1, out messages1);
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            //不保存对打开模板的修改 
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            //结束打印引擎                  
            btEngine.Stop();
        }
        /// <summary>
        /// 隐藏tab页
        /// </summary>
        public Frm样衣订单预览 HideTabcontrol()
        {
            this.xtraTabPage任务.PageVisible = false;
            this.xtraTabPage量体值.PageVisible = false;
            this.xtraTabPage面料.PageVisible = false;
            //this.ribbonControl1.Visible = false;
            //this.fileRibbonPage1.Visible = false;
            //this.ribbonPage样品任务.Visible = false;
            this.dockPanel任务流程.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            return this;
        }
        public Frm样衣订单预览 HideFor任务()
        {
            this.dockPanel任务流程.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            return this;
        }
        /// <summary>
        /// 隐藏按键
        /// </summary>
        /// <returns></returns>
        public Frm样衣订单预览 HideButton()
        {
            //this.barButtonItem4.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            return this;
        }
        public Frm样衣订单预览 HideFor样衣()
        {
            //this.barButtonItem4.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            this.xtraTabPage任务.PageVisible = false;
            return this;
        }

        private void treeList任务流程_RowCellClick(object sender, DevExpress.XtraTreeList.RowCellClickEventArgs e)
        {
            switch (Convert.ToInt32(this.treeList任务流程.FocusedNode.GetValue("template_id").ToString()))
            {
                case (int)Enum样衣子任务.面料任务:
                    new Frm样品面料任务(this.treeList任务流程.FocusedNode.GetValue("order_id").ToString(),this.dto面料样品).ShowDialog();
                    break;
                case (int)Enum样衣子任务.设计点任务:
                    new Frm样品设计点任务(this.ORDER_ID).ShowDialog();
                    break;
                case (int)Enum样衣子任务.尺寸任务:
                    new Frm样品尺寸任务().ShowDialog();
                    break;
            }

        }

        private void tileItem1_ItemClick(object sender, DevExpress.XtraEditors.TileItemEventArgs e)
        {
            //new 门店下单选款式Report().;
            DTO样衣订单导出 dTO样衣订单导出 = OrderService.getSampleOrder(this.ORDER_ID, this.imageUtil);
            List<DTO样衣订单导出> dTO样衣订单导出s = new List<DTO样衣订单导出>();
            dTO样衣订单导出s.Add(dTO样衣订单导出);
            XtraReport样衣订单 report = new XtraReport样衣订单();
            report.DataSource = dTO样衣订单导出s;
            //PrintHelper.Print(report);

            ReportPrintTool tool = new ReportPrintTool(report);
            tool.ShowPreview();
        }

        private void tileItem上传图片_ItemClick(object sender, DevExpress.XtraEditors.TileItemEventArgs e)
        {
            this.imageUtil = FileService.updateTempalteFile(MIMEConst.IMAGE_MIME, this.imageUtil);
            this.pictureBoxImage.Image = this.imageUtil.image;
        }
    }
}
